<template>
    <n-drawer v-model:show="visible" v-bind="mergedProps">
        <n-drawer-content v-bind="contentProps">
            <template #header>
                <slot name="header">{{ mergedTitle }}</slot>
            </template>
            <slot></slot>
            <template #footer>
                <slot name="footer">
                    <GetanButtonGroup :options="defaultActions" />
                </slot>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script setup lang="ts">
import { isEmpty, isUndefined } from "@/utils"
import { DrawerMethods, GetanDrawerProps } from "./types"
import { useActions } from "./hooks/useActions"
import { GetanButtonGroup } from "@/components/ButtonGroup"

const attrs = useAttrs()
const props = defineProps<{ options?: GetanDrawerProps }>()
const propsRef = ref<Partial<GetanDrawerProps>>({})

const titleRef = ref<string>("")
const mergedTitle = computed(() => (isEmpty(titleRef.value) ? unref(mergedOptions).title : unref(titleRef)))

const mergedOptions = computed(() => {
    return {
        ...props.options,
        ...unref(propsRef)
    }
})

function parseProps(options: Ref<GetanDrawerProps>) {
    const { resizable, placement, maskClosable } = unref(options)
    return {
        resizable,
        placement,
        maskClosable,
        width: unref(options).width ?? "600px"
    }
}

const mergedProps = computed(() => {
    return {
        ...attrs,
        ...(isEmpty(unref(mergedOptions)) ? {} : parseProps(mergedOptions))
    } as Recordable
})

const contentProps = computed(() => {
    return {
        headerStyle: { padding: "15px" },
        footerStyle: { padding: "10px 15px", justifyContent: "flex-start" },
        closable: unref(mergedOptions).closable ?? !isUndefined(unref(mergedOptions).title)
    }
})

const emits = defineEmits(["on-close", "on-ok", "on-cancel", "register"])
const visible = ref<boolean>(false)
const { defaultActions } = useActions(mergedOptions, visible, emits)

function openDrawer(title?: string) {
    title && (titleRef.value = title)
    visible.value = true
}

function closeDrawer() {
    visible.value = false
}

function init(registerProps: Partial<GetanDrawerProps>) {
    propsRef.value = registerProps ?? {}
}

const methods: DrawerMethods = {
    init,
    open: openDrawer,
    close: closeDrawer
}

const instance = getCurrentInstance()
if (instance) {
    emits("register", methods)
}
</script>
